import logging
from logging import handlers
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware, Request, Response

from config import settings


logger = logging.getLogger("system.logging")
logger.setLevel(settings.DEBUG_LEVEL)

ch = logging.StreamHandler()
fh = handlers.RotatingFileHandler("./logs/system.log", mode="a", maxBytes=100*1024, backupCount=2)

formatter = logging.Formatter(
    "%(levelname)s - [%(asctime)s] %(module)s->%(filename)s(line %(lineno)d): %(message)s"
)

ch.setFormatter(formatter)
fh.setFormatter(formatter)

logger.addHandler(ch)       # 将日志输出至屏幕
logger.addHandler(fh)       # 将日志输出至文件


def add_log_requests_middle(app: FastAPI):
    app.add_middleware(BaseHTTPMiddleware, dispatch=log_requests)


async def log_requests(request: Request, call_next):

    response: Response = await call_next(request)

    return response
